<template>
  <div class="edit-page-wrap">
    <Head title="电站信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="限制站点" prop="stationType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.stationType"
              v-for="(item, index) in optionsS.stationType"
              :key="index"
              @change="handleStationType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.stationType === '2'
                  ? '选定运营商后，该运营商所有的电站均在白名单中'
                  : '选定单电站后，仅所选电站在白名单中'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '2'"
            label=""
            prop="treeOrgs"
          >
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.treeOrgs"
              :data="optionsS.org"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '1'"
            label=""
            prop="treeStations"
          >
            <QcTree
              ref="treeStationRef"
              :setCheckedKeys="ruleForm.treeStations.split(',')"
              :data="optionsS.station"
              :showCheckbox="true"
              @handleCheck="handleCheckStation"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="限制规则">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="限制日期" prop="dates">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.dates"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                @change="handleChangeTimes"
              />
            </div>
          </el-form-item>
          <el-form-item label="限制周天" prop="restrictedDays">
            <el-checkbox-group
              v-model="ruleForm.restrictedDays"
              @change="handleChangeDay"
            >
              <el-checkbox
                v-for="item in optionsS.week"
                :key="item.value"
                :label="item.label"
                :disabled="item.disabled"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div class="time-wrap">
            <el-form-item label="每日时段" prop="startTimeFrame">
              <QcTimeSelect
                :value="ruleForm.startTimeFrame"
                start="00:00"
                step="00:30"
                end="23:30"
                :max-time="ruleForm.endTimeFrame"
                placeholder="请选择开始时间"
                @change="handleStartTime"
              />
            </el-form-item>
            <el-form-item label="" prop="endTimeFrame" label-width="12px">
              <QcTimeSelect
                :value="ruleForm.endTimeFrame"
                start="00:30"
                step="00:30"
                end="24:00"
                :min-time="ruleForm.startTimeFrame"
                placeholder="请选择结束时间"
                @change="handleEndTime"
              />
            </el-form-item>
          </div>
        </el-form>
      </template>
    </Head>
    <Head title="限制机构">
      <template #content>
        <el-form
          ref="ruleFormRef2"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="限制用户" prop="userType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.userType"
              v-for="(item, index) in optionsS.userType"
              :key="index"
              @change="handleUserType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div v-if="ruleForm.userType" class="tip">
              <div class="icon"></div>
              {{
                ruleForm.userType === '3'
                  ? '选定企业后，该企业所有用户均在白名单中，含企业新增用户'
                  : ruleForm.userType === '4'
                  ? '选定标签后，该标签内所有用户均在白名单中，标签用户添加、删除会同步更新'
                  : ruleForm.userType === '5'
                  ? '注：输入的用户账号，多个账号之间用英文“,”隔开'
                  : ''
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.userType === '3'"
            label=""
            prop="treeVehicles"
          >
            <QcTree
              ref="treeVehiclesRef"
              :setCheckedKeys="ruleForm.treeVehicles"
              :data="optionsS.vehicle"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckVehicles"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.userType === '4'"
            label=""
            prop="treeLabels"
          >
            <QcTree
              ref="treeLabelRef"
              :setCheckedKeys="ruleForm.treeLabels.split(',')"
              :data="optionsS.label"
              :showCheckbox="true"
              @handleCheck="handleCheckLabel"
            ></QcTree>
          </el-form-item>
          <el-form-item label="" v-if="ruleForm.userType == '5'">
            <el-button type="primary" plain @click="clickUploadUser"
              >批量导入</el-button
            >
          </el-form-item>
          <el-form-item prop="importUsers" v-if="ruleForm.userType == '5'">
            <el-input
              v-model.trim="ruleForm.importUsers"
              placeholder="请输入用户账号"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
    <ImportDialog ref="importDialogRef" @user-data="userData"></ImportDialog>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import QcTimeSelect from '@/components/qcTimeSelect/index.vue';
import ImportDialog from '@/components/qcDialog/importDialog.vue';
import { queryDicByParent } from '@/service/apis/api';
import {
  stationTreeDataByChannel,
  queryCarList,
  queryVehicleWhite,
  queryLabelListByName,
} from '@/service/apis/org';
import {
  addWhiteList,
  updateWhiteList,
  getWhiteList,
} from '@/service/apis/pile';
import { WEEK } from '@/utils/dictionaries';
import { getWeek } from '@/utils/utils';
import { FormInstance, FormRules } from 'element-plus';
import { cloneDeep } from 'lodash';
import { NO_CHINESE_COMMA } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();
const importDialogRef = ref();
const treeOrgRef = ref();
const treeVehiclesRef = ref();

const optionsS = reactive({
  stationType: [] as any,
  userType: [] as any,
  org: [] as any,
  station: [] as any,
  vehicle: [] as any,
  label: [] as any,
  week: cloneDeep(WEEK) as any,
});

queryDicByParent({
  listDtos: ['whiteListStationType', 'whiteListUserType'],
}).then((res: any) => {
  if (res) {
    optionsS.stationType = res.whiteListStationType.sort(
      (a: any, b: any) => Number(b.value) - Number(a.value)
    );
    optionsS.userType = res.whiteListUserType;
  }
});

// 获取电站运营商树
const getOrgs = () => {
  queryCarList({}).then((res: any) => {
    if (res) {
      optionsS.org = res;
    }
  });
};

// 获取电站树
const getStations = () => {
  stationTreeDataByChannel({ cecType: 2 }).then((res: any) => {
    if (res) {
      optionsS.station = res;
    }
  });
};

// 获取车辆机构
const getVehicle = () => {
  queryVehicleWhite({}).then((res: any) => {
    if (res) {
      optionsS.vehicle = res;
    }
  });
};

// 获取标签
const getLabel = () => {
  queryLabelListByName({}).then((res: any) => {
    if (res) {
      optionsS.label = res.listMap;
    }
  });
};

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};

const ruleForm: any = reactive({
  id: '',
  name: '', // 名称
  stationType: '2', //限制站点
  stationIds: '', //限制站点数据ids
  treeOrgs: [] as any, //限制站点数据-运营商-树
  treeStations: '', //限制站点数据-电站树
  startDate: '', // 限制日期-开始日期
  endDate: '', //限制日期-结束日期
  dates: [] as any, //限制日期-组件
  restrictedDay: '', // 限制周天 0~6
  restrictedDays: [] as any, // 限制周天-多选组件
  startTimeFrame: undefined as any, // 每日时段-开始时间
  endTimeFrame: undefined as any, // 每日时段-结束时间
  userType: '', //限制用户
  astrictIds: '', //限制用户ids
  treeVehicles: [] as any, //限制用户-机构树
  treeLabels: '', //限制用户-标签树
  importUsers: '', // 导入或编辑的用户数据
});
const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (ruleForm.userType === '3' && treeOrg.length > 0 && arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  stationType: [
    { required: true, message: '请选择限制站点', trigger: ['blur', 'change'] },
  ],
  treeOrgs: [
    { required: true, message: '请选择运营商', trigger: ['blur', 'change'] },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  treeStations: [
    { required: true, message: '请选择电站', trigger: ['blur', 'change'] },
  ],
  dates: [
    { required: true, message: '请选择限制日期', trigger: ['blur', 'change'] },
  ],
  restrictedDays: [
    { required: true, message: '请选择限制周天', trigger: ['blur', 'change'] },
  ],
  startTimeFrame: [
    { required: true, message: '请选择开始时间', trigger: ['blur', 'change'] },
  ],
  endTimeFrame: [
    { required: true, message: '请选择结束时间', trigger: ['blur', 'change'] },
  ],
  importUsers: [
    { pattern: NO_CHINESE_COMMA, message: '不能输入中文逗号', trigger: 'blur' },
  ],
  treeVehicles: [{ validator: checkTreeVehicles, trigger: ['blur', 'change'] }],
});

const handleChangeDay = (e: any) => {
  ruleForm.restrictedDays = e;
};

const handleStartTime = (e: any) => {
  ruleForm.startTimeFrame = e;
};
const handleEndTime = (e: any) => {
  ruleForm.endTimeFrame = e;
};

const handleChangeTimes = (e: any) => {
  if (e?.length === 2) {
    optionsS.week = getWeek(e, WEEK);
  } else {
    optionsS.week = cloneDeep(WEEK);
  }
  ruleForm.restrictedDays = [];
};

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeOrgs = checkedChildData;
  ruleFormRef.value?.validateField('treeOrgs');
};
const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeStations = checkedChildData.toString();
  ruleFormRef.value?.validateField('treeStations');
};
const handleCheckVehicles = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeVehicles = checkedChildData;
  ruleFormRef2.value?.validateField('treeVehicles');
};
const handleCheckLabel = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeLabels = checkedChildData.toString();
};

const clickUploadUser = () => {
  importDialogRef.value?.show();
};

const handleStationType = (val: any) => {
  if (val === '2' && optionsS.org.length === 0) {
    getOrgs();
  } else if (val === '1' && optionsS.station.length === 0) {
    getStations();
  }
};
const handleUserType = (val: any) => {
  if (val === '3' && optionsS.vehicle.length === 0) {
    getVehicle();
  } else if (val === '4' && optionsS.label.length === 0) {
    getLabel();
  }
};

const userData = (data: any) => {
  ruleForm.importUsers = data;
};

if (id) {
  getWhiteList(id).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      //限制站点树
      if (ruleForm.stationType === '1') {
        ruleForm.treeStations = res.stationIds;
        getStations();
      } else if (ruleForm.stationType === '2') {
        ruleForm.treeOrgs = res.stationIds.split(',');
        getOrgs();
      }
      // 签约时间
      ruleForm.dates = [res.startDate, res.endDate];
      // 限制周天
      const arr = [] as any;
      WEEK.forEach((item: any) => {
        if (res.restrictedDay.includes(item.value)) {
          arr.push(item.label);
        }
      });
      ruleForm.restrictedDays = arr;
      optionsS.week = getWeek(ruleForm.dates, WEEK);
      //限制用户树
      if (ruleForm.userType === '3') {
        ruleForm.treeVehicles = res.astrictIds.split(',');
        getVehicle();
      } else if (ruleForm.userType === '4') {
        ruleForm.treeLabels = res.astrictIds;
        getLabel();
      } else if (ruleForm.userType === '5') {
        ruleForm.importUsers = res.astrictIds;
      }
    }
  });
} else {
  getOrgs();
  getVehicle();
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value || !ruleFormRef2.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef2.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        ruleFormRef2.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  // 时间区间
  ruleForm.startDate = ruleForm.dates[0];
  ruleForm.endDate = ruleForm.dates[1];
  // 周期
  const arr = [] as any;
  const str = ruleForm.restrictedDays.toString();
  WEEK.forEach((item: any) => {
    if (str.includes(item.label)) {
      arr.push(item.value);
    }
  });
  ruleForm.restrictedDay = arr.toString();
  // 电站树
  if (ruleForm.stationType === '2') {
    // ruleForm.stationIds = ruleForm.treeOrgs;
    const arr: any = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.stationIds = arr.toString();
  } else {
    ruleForm.stationIds = ruleForm.treeStations;
  }
  // 用户树
  if (ruleForm.userType === '3') {
    // ruleForm.astrictIds = ruleForm.treeVehicles;
    const arr: any = [];
    const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.astrictIds = arr.toString();
  } else if (ruleForm.userType === '4') {
    ruleForm.astrictIds = ruleForm.treeLabels;
  } else if (ruleForm.userType === '5') {
    ruleForm.astrictIds = ruleForm.importUsers;
  }
  console.log('rr----', ruleForm);
  if (id) {
    updateWhiteList(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addWhiteList(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>

<style lang="scss" scoped>
.time-wrap {
  display: flex;
  :deep(.el-select-v2) {
    width: 144px !important;
    .el-select-v2__wrapper {
      height: 32px;
    }
  }
  :deep(.el-form-item:last-child .el-form-item__content) {
    padding-left: 0;
    .el-form-item__error {
      padding-left: 0;
    }
  }
}
</style>